angular.module('canal', [])
    .controller('canalCtrl', ['$scope', 'httpService', '$localStorage', 'alertmsg', 'confirmservice', function($scope, httpService, $localStorage, alertmsg, confirmservice) {
        $scope.isAdd = false;
        var company_id;
        // 获取渠道列表
        function getCanals(company_id) {
            httpService.query('web/fetch_regions', { company_id: company_id, limit: 999 }).then(function(res) {
                if (res.code == 200) {
                    $scope.canals = res.regions;
                }
            });
        }

        if ($localStorage.user) {
            company_id = $localStorage.user.company_id;
            getCanals(company_id);
        }

        // 添加渠道
        $scope.addCanal = function(content) {
        	if(content) {
        		var obj = {
	                notice_type: 'region',
	                resource_id: company_id,
	                content: content
	            };
	            httpService.query('web/region', obj, 'post').then(res => {
	                if (res.code == 200) {
	                    $scope.content = '';
	                    $scope.isAdd = false;
	                    getCanals(company_id);
	                    alertmsg('添加渠道' + content + '成功！');
	                } else {
	                    alertmsg('添加渠道' + content + '失败！原因:' + res.msg);
	                }
	            });
        	} else {
        		alertmsg('请输入渠道名！');
        	}
	            
        };

        $scope.cancelCanal = function() {
            $scope.isAdd = false;
        };

        // 删除渠道
        $scope.deleteCanal = function(canal, index) {
            confirmservice('是否删除？').then(function(bool) {
                if (bool) {
                    var obj = {
                        type: 'delete',
                        notice_type: 'region',
                        resource_id: company_id,
                        content: canal.content,
                        id: canal.id
                    };
                    httpService.query('web/manager_region', obj, 'post').then(res => {
                        if (res.code == 200) {
                            $scope.canals.splice(index, 1);
                            alertmsg('删除渠道' + canal.content + '成功！');
                        } else {
                            alertmsg('删除渠道失败！原因:' + res.msg);
                        }
                    });
                }
            });
        };

    }]);
